/*Scala code license:

 Copyright 2009/10 Osman Pub

 Licensed under the Apache License, Version 2.0 (the "License") you may not use
 this file except in compliance with the License.

 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software distributed
 under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 CONDITIONS OF ANY KIND, either express or implied. See the License for the
 specific language governing permissions and limitations under the License.

 */
/**
 Orginal java code credits:
 * Image loading class that converts BufferedImages into a data
 * structure that can be easily passed to OpenGL.
 * @author Pepijn Van Eeckhoudt
 */
package common

import com.sun.opengl.util.BufferUtil
import javax.imageio.ImageIO
import java.awt.image._
import java.io._
import java.nio.ByteBuffer

object TextureReader {
  def readTexture(filename: String): Texture = readTexture(filename, false)
  def readTexture(filename: String, storeAlphaChannel: Boolean): Texture  = {
    val bufferedImage = ImageIO read(getResourceAsStream(filename))
    readPixels(bufferedImage, storeAlphaChannel)
  }

  private def getResourceAsStream(filename: String): InputStream =
    getClass getClassLoader() getResourceAsStream filename

  private def readPixels(img: BufferedImage, storeAlphaChannel: Boolean): Texture = {
    val packedPixels = new Array[Int](img.getWidth * img.getHeight)

    val pixelgrabber =
      new PixelGrabber(img, 0, 0, img getWidth, img getHeight, packedPixels, 0,
                       img getWidth)
    try { pixelgrabber grabPixels }
    catch { case e: Exception => throw new RuntimeException }

    val bytesPerPixel = if(storeAlphaChannel) 4 else 3
    val unpackedPixels = BufferUtil newByteBuffer(packedPixels.length *
                                                  bytesPerPixel)

    for(row <- img.getHeight - 1 to 0 by -1)
      for(col <- 0 until img.getWidth) {
        val packedPixel = packedPixels(row * img.getWidth + col)
        unpackedPixels put(((packedPixel >> 16) & 0xFF).asInstanceOf[Byte])
        unpackedPixels put(((packedPixel >> 8) & 0xFF).asInstanceOf[Byte])
        unpackedPixels put(((packedPixel >> 0) & 0xFF).asInstanceOf[Byte])
        if(storeAlphaChannel)
          unpackedPixels put(((packedPixel >> 24) & 0xFF).asInstanceOf[Byte])
      }

    unpackedPixels flip;
    new Texture(unpackedPixels, img getWidth, img getHeight)
  }

  class Texture(var pixels: ByteBuffer, var width: Int, var height: Int) {}
}